package com.woman.beautylive.presentation.ui.widget;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.woman.beautylive.R;
import com.woman.beautylive.data.bean.me.UserInfo;
import com.woman.beautylive.data.bean.room.RoomAdminInfo;
import com.woman.beautylive.data.repository.SourceFactory;
import com.woman.beautylive.data.websocket.WebSocketService;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.main.me.OtherUserActivity;
import com.woman.beautylive.presentation.ui.room.RoomManageDialog;
import com.woman.beautylive.presentation.ui.room.publish.PublishFragment;
import com.woman.beautylive.util.DownLoadUtil;
import com.woman.beautylive.util.L;
import com.woman.beautylive.util.PicUtil;

import java.util.List;

/**
 * Created by huanzhang on 2016/4/10.
 */
public class UserInfoDialog extends Dialog implements View.OnClickListener, IUserInfoDialog {
    private SimpleDraweeView mPhoto, mMin;
    private Context context;
    private TextView mNickName,mId, mAddr, mCertification, mBrief, mStarNum, mFansNum, mSentNum,mGetNum;
    //               关注                    管理按钮
    private TextView mStarBtn, mMainPageBtn, mCompaint,mPrvChat;
//    关注私信和回复主页上面的那个分割线
    private View line;
//  关注私信和回复主页的父容器 用于管理隐藏和显示
    private LinearLayout mTabBottom;
    private ImageView mCancel;
    private ProgressDialog mProgressDialog;
    public String nicName;

    private UserInfoDialogPresenter mPresenter;
    private String mUserId = null;
    private UserInfo minfo;
    private UserClickKickListener mKickListener;
    private boolean isShowKick = false;
    private ChatListener listener;
    private WebSocketService webService;

    private RoomManageDialog roomManageDialog;
    //    管理员列表
    private List<RoomAdminInfo> adminInfoList;
    //    是否是管理员
    private boolean isadmin = false;
//    当前登录的id
    private String token;
//    当前房间的主播id
    private String uid;

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    private String roomid;
    public UserInfoDialog(Context context) {
        super(context, R.style.DialogStyle);
        this.context = context;
    }

    public UserInfoDialog(Context context, WebSocketService webService,String mAnchorId,String mRoomId, ChatListener listener) {
        super(context, R.style.DialogStyle);
        this.context = context;
        this.webService = webService;
        this.uid=mAnchorId;
        this.roomid=mRoomId;
        this.listener = listener;
    }
    public UserInfoDialog(Context context, WebSocketService webService,String mAnchorId) {
        super(context, R.style.DialogStyle);
        this.context = context;
        this.webService = webService;
        this.uid=mAnchorId;
    }
    public UserInfoDialog(Context context, WebSocketService webService,String mAnchorId,int themeResId) {
        super(context, R.style.DialogStyle);
        this.context = context;
        this.webService = webService;
        this.uid=mAnchorId;
    }

    public UserInfoDialog(Context context, int themeResId) {
        super(context, R.style.DialogStyle);
        this.context = context;
    }

    protected UserInfoDialog(Context context, boolean themeResId, ChatListener listener) {
        super(context, R.style.DialogStyle);
        this.context=context;
        this.listener = listener;
    }
    public interface ChatListener{
        /**
         * 回调函数，用于在Dialog的监听事件触发后刷新Activity的UI显示
         */
        public void prvChatListener();
    }
    public void setUserInofo(UserInfo info) {
        this.minfo = info;
    }

    public void setKickListener(UserClickKickListener listener) {
        mKickListener = listener;
    }

    public void showKick(boolean isShow) {
        isShowKick = isShow;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.dialog_userinfo);
        findView();
        initShowManager();
//        init();
    }

    private void findView() {
        mPhoto = (SimpleDraweeView) findViewById(R.id.dialog_user_info_photo);
        mMin = (SimpleDraweeView) findViewById(R.id.dialog_user_info_photo_min);
        mId= (TextView) findViewById(R.id.dialog_user_info_userid);
        mNickName = (TextView) findViewById(R.id.dialog_user_info_name);
        mAddr = (TextView) findViewById(R.id.dialog_user_info_addr);
        mCertification = (TextView) findViewById(R.id.dialog_user_info_certification);
        mBrief = (TextView) findViewById(R.id.dialog_user_info_signature);
        mGetNum= (TextView) findViewById(R.id.dialog_user_info_poll_num);
        mStarNum = (TextView) findViewById(R.id.dialog_user_info_star_num);
        mFansNum = (TextView) findViewById(R.id.dialog_user_info_fans_num);
        mSentNum = (TextView) findViewById(R.id.dialog_user_info_sent_num);
        mStarBtn = (TextView) findViewById(R.id.dialog_user_info_star);
        mMainPageBtn = (TextView) findViewById(R.id.dialog_user_info_mainpage);
        mCancel = (ImageView) findViewById(R.id.dialog_user_info_cancel);
        mCompaint = (TextView) findViewById(R.id.dialog_user_info_complaint);
        mPrvChat=(TextView)findViewById(R.id.dialog_user_info_prv_chat);
        line=findViewById(R.id.dialog_user_info_line);
        mTabBottom= (LinearLayout) findViewById(R.id.dialog_user_tab_bottom);
    }

    private void initShowManager() {
        Log.i("mrl",minfo.getIsHit()+"这个是否被拉黑");
        if(uid!=null) {
            if (uid.equals(LocalDataManager.getInstance().getLoginInfo().getUserId()) && minfo.getIsHit() == 1) {
                mMainPageBtn.setText("已拉黑");
            } else if (uid.equals(LocalDataManager.getInstance().getLoginInfo().getUserId()) && minfo.getIsHit() == 0) {
                mMainPageBtn.setText("拉黑");
            } else {
                mMainPageBtn.setText("主页");
            }
        }
        if (mUserId!=null||minfo!=null) {
            //            如果查看的资料是自己那么久隐藏
            if (mUserId.equals(LocalDataManager.getInstance().getLoginInfo().getUserId())||minfo.getId().equals(LocalDataManager.getInstance().getLoginInfo().getUserId())) {
                mCompaint.setVisibility(View.INVISIBLE);
                line.setVisibility(View.INVISIBLE);
                mTabBottom.setVisibility(View.INVISIBLE);
            }
        }
        mPresenter = new UserInfoDialogPresenter(this);
        token = LocalDataManager.getInstance().getLoginInfo().getToken();
        mPresenter.getAdminList(token, uid);
        init();
    }

    private void init() {
        Log.i("mrl","有没有加载哦"+System.currentTimeMillis());
        if (minfo != null) {
//            if (isadmin || info.getId().equals(uid)) {
//                mCompaint.setVisibility(View.VISIBLE);
//            } else {
//                mCompaint.setText(R.string.jubao);
//            }
            mCancel.setOnClickListener(this);
            mStarBtn.setOnClickListener(this);
            mMainPageBtn.setOnClickListener(this);
            mCompaint.setOnClickListener(this);
            mPrvChat.setOnClickListener(this);
            showUserInfo(minfo);
            mPresenter.loadUserInfo(mUserId);
        }
    }
    public void setUserId(String id) {
        Log.i("mrl","这个先？setUserId"+System.currentTimeMillis());
        mUserId = id;
    }

    private void setListener() {

    }

    @Override
    public void onClick(View v) {
        if (v == mCancel) {
            dismiss();
        }
        if (v == mStarBtn) {
            if (mStarBtn.getTag() == null) {
                CustomToast.makeCustomText(this.getContext(), "用户数据异常", CustomToast.LENGTH_SHORT).show();
                return;
            }
            if (Integer.parseInt(mStarBtn.getTag().toString()) == 1) {
                unStarUser();
            } else {
                starUser();
            }
        }
        //        拉黑或者是主页
        if (v == mMainPageBtn&&mMainPageBtn.getText().toString().equals("主页")) {
            goUserMainPage();
        }else if (v== mMainPageBtn&&mMainPageBtn.getText().toString().equals("拉黑")){
            if (minfo.getId()!=null) {
//                拉黑
                mPresenter.setHit(token, minfo.getId());
            }
        }else if (v== mMainPageBtn&&mMainPageBtn.getText().toString().equals("已被拉黑")){
            Log.i("mrl","没进来吧");
//            接触拉黑
            mPresenter.removeHit(token,minfo.getId());
        }
        if (v == mCompaint) {
//            if (isadmin||info.equals(uid)) {
                roomManageDialog = new RoomManageDialog(context, webService,minfo,token,uid);
                Window win = roomManageDialog.getWindow();
                win.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = win.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.MATCH_PARENT;
                win.setAttributes(lp);
                roomManageDialog.show();

//                这里改变成管理功能
//                showPopWindow();
//                mKickListener.clickKick(info.getId(), info.getNickname());
//            } else {
//                dismiss();
//                CustomToast.makeCustomText(this.getContext(), "已举报", CustomToast.LENGTH_SHORT).show();
//            }
        }
        if (v==mPrvChat){
            dismiss();
            listener.prvChatListener();
        }

    }

    private void starUser() {
        if (uid.equals(minfo.getId())) {
            mPresenter.starUser(LocalDataManager.getInstance().getLoginInfo().getToken(), mUserId, String.valueOf(roomid));
        }else {
            mPresenter.starUser(LocalDataManager.getInstance().getLoginInfo().getToken(), mUserId,"");
        }
//        mStarBtn.setTextColor(getContext().getResources().getColor(R.color.colorSecondaryText));
//        mStarBtn.setText(getContext().getResources().getString(R.string.is_star));
//        mStarBtn.setTag(1);
    }

    private void unStarUser() {
        if (uid.equals(minfo.getId())) {
            mPresenter.unStarUser(LocalDataManager.getInstance().getLoginInfo().getToken(), mUserId, String.valueOf(roomid));
        }else {
            mPresenter.unStarUser(LocalDataManager.getInstance().getLoginInfo().getToken(), mUserId, "");
        }
//        mStarBtn.setTextColor(getContext().getResources().getColor(R.color.txt_color));
//        mStarBtn.setText(getContext().getResources().getString(R.string.star));
//        mStarBtn.setTag(0);
    }

    private void goUserMainPage() {
        PublishFragment.isCameraManagerPause = false;
        this.getContext().startActivity(OtherUserActivity.createIntent(getContext(), Integer.parseInt(mUserId), false));
        this.dismiss();
    }

    @Override
    public void showUserInfo(UserInfo info) {
        L.e("lw","ui+"+info);
        if (info == null) {
            CustomToast.makeCustomText(this.getContext(), "用户数据异常", CustomToast.LENGTH_SHORT).show();
            dismiss();
        } else {
            this.minfo = info;

            if (info.getAvatar() != null) {
               /* FrescoUtil.frescoResize(
                        SourceFactory.wrapPathToUri(info.getAvatar()),
                        (int) this.getContext().getResources().getDimension(R.dimen.user_photo_size),
                        (int) this.getContext().getResources().getDimension(R.dimen.user_photo_size),
                        mPhoto
                );*/
                mPhoto.setImageURI(SourceFactory.wrapPathToUri(info.getAvatar()));
            }
            if (info.getNickname() != null) {
                mNickName.setText(info.getNickname() + " ");
            }
            PicUtil.TextViewSpandImg(this.getContext(),
                    mNickName,
                    info.getSex() == 0 ? R.drawable.ic_male : R.drawable.ic_female
                    , R.dimen.sex_icon_size, R.dimen.sex_icon_size);

            if (info.getId()!=null){
                mId.setText("ID号: "+info.getId());
            }

            if (info.getIntro() != null) {
                mBrief.setText(info.getIntro());
            }
//            if (info.getTotalContribution() != 0) {
                mSentNum.setText(getContext().getResources().getString(R.string.userinfo_dialog_sent));
                mSentNum.append(DownLoadUtil.conversionNumber(info.getTotalContribution())+" ");
                PicUtil.TextViewSpandImg(this.getContext(), mSentNum, R.drawable.ic_me_myaccount_reddiamond);
//            }

            mGetNum.setText(getContext().getResources().getString(R.string.userinfo_dialog_poll));
            mGetNum.append(DownLoadUtil.conversionNumber(Integer.parseInt(info.getEarnbean())));

            mStarNum.setText(getContext().getResources().getString(R.string.userinfo_dialog_star));
            mStarNum.append(DownLoadUtil.conversionNumber(Integer.parseInt(info.getFolloweesCount())));
            mFansNum.setText(getContext().getResources().getString(R.string.userinfo_dialog_fans));
            mFansNum.append(info.getFollowersCount());


            // mLevelTip.setText(info.getLevel());
            Context context = this.getContext();

            int resId = context.getResources().getIdentifier("rank_" + info.getLevel(), "drawable", context.getPackageName());
            mNickName.append(" ");
            PicUtil.TextViewSpandImg(context, mNickName, resId, R.dimen.level_width, R.dimen.level_height);


            mAddr.setText("");
            PicUtil.TextViewSpandImg(context, mAddr, R.drawable.ic_room_pop_up_location
                    , R.dimen.city_width, R.dimen.city_height);
            mAddr.append(info.getCity() == null ? this.getContext().getResources().getString(R.string.city_tip) : info.getCity());

//            mCertification.setText("");
//            PicUtil.TextViewSpandImg(context,mCertification,R.drawable.ic_me_renzheng
//            ,R.dimen.city_height,R.dimen.city_height);
//            mCertification.append(context.getResources().getString(R.string.userinfo_dialog_certification));
            Log.i("mrl",info.getIsAttention()+"初始化关注"+info.getNickname()+info.toString());
            if (info.getIsAttention() == 1) {
                mStarBtn.setTextColor(context.getResources().getColor(R.color.colorSecondaryText));
                mStarBtn.setText(context.getResources().getString(R.string.is_star));
                mStarBtn.setTag(1);
            } else {
                mStarBtn.setTextColor(context.getResources().getColor(R.color.txt_color));
                mStarBtn.setText(context.getResources().getString(R.string.star));
                mStarBtn.setTag(0);
            }

            Log.i("mrl",minfo.getIsHit()+"这个是否被拉黑");
            if (uid.equals(LocalDataManager.getInstance().getLoginInfo().getUserId())&&minfo.getIsHit()==1){
                mMainPageBtn.setText("已拉黑");
            }else if (uid.equals(LocalDataManager.getInstance().getLoginInfo().getUserId())&&minfo.getIsHit()==0){
                mMainPageBtn.setText("拉黑");
            }else {
                mMainPageBtn.setText("主页");
            }
            Log.i("mrl",info.getTopContributeUsers()+"排行榜");
//            排行榜第一个的
            if (info.getTopContributeUsers()!=null&&info.getTopContributeUsers().size()>0){
                mMin.setVisibility(View.VISIBLE);
//                int avatarSize = (int) context.getResources().getDimension(R.dimen.avatar_size_default);
//                FrescoUtil.frescoResize(SourceFactory.wrapPathToUri(info.getTopContributeUsers().get(0)),
//                        avatarSize, avatarSize, topContributeDrawees.get(i));
                mMin.setImageURI(SourceFactory.wrapPathToUri(info.getTopContributeUsers().get(0)));
            }else {
                mMin.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    public void getAdminLists(List<RoomAdminInfo> adminList) {
        Log.i("mrl","掉用了");
        if (adminList != null) {
            Log.i("mrl", adminList.size() + " 这个是管理员列表");
            for (int i = 0; i < adminList.size(); i++) {
//                判断当前用户是否是该房间的管理员
                if (uid.equals(adminList.get(i).getId())) {
                    isadmin = true;
                    return;
                }
            }
        } else {

        }
    }

    @Override
    public void adminnullgoinit() {
        mCompaint.setEnabled(true);
    }

    @Override
    public void getHitCode(int code) {
        if (code==0&&uid.equals(LocalDataManager.getInstance().getLoginInfo().getUserId())){
            minfo.setIsHit(1);
            CustomToast.makeCustomText(context,"拉黑成功", Toast.LENGTH_SHORT).show();
            mMainPageBtn.setText("已被拉黑");
            mStarBtn.setTextColor(getContext().getResources().getColor(R.color.txt_color));
            mStarBtn.setText(getContext().getResources().getString(R.string.star));
            mStarBtn.setTag(0);
        }
    }

    @Override
    public void getRemoveHitCode(int code) {
        Log.i("mrl","解除拉黑");
        if (code==0&&uid.equals(LocalDataManager.getInstance().getLoginInfo().getUserId())){
            minfo.setIsHit(0);
            mMainPageBtn.setText("拉黑");
            CustomToast.makeCustomText(context,"解除拉黑成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getStartCode(int code) {
        if (code==0){
            CustomToast.makeCustomText(context,"关注成功", Toast.LENGTH_SHORT).show();
            mStarBtn.setTextColor(getContext().getResources().getColor(R.color.colorSecondaryText));
            mStarBtn.setText(getContext().getResources().getString(R.string.is_star));
            mStarBtn.setTag(1);
            if (uid.equals(LocalDataManager.getInstance().getLoginInfo().getUserId())) {
                minfo.setIsHit(0);
                mMainPageBtn.setText("拉黑");
            }
        }else {
            CustomToast.makeCustomText(context,"关注失败咯", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getRemoveStartCode(int code) {
        if (code==0){
            CustomToast.makeCustomText(context,"解除关注成功", Toast.LENGTH_SHORT).show();
            mStarBtn.setTextColor(getContext().getResources().getColor(R.color.txt_color));
            mStarBtn.setText(getContext().getResources().getString(R.string.star));
            mStarBtn.setTag(0);
        }else {
            CustomToast.makeCustomText(context,"取消关注失败咯", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void showDataException(String msg) {
        CustomToast.makeCustomText(this.getContext(), msg, CustomToast.LENGTH_SHORT).show();
    }

    @Override
    public void showNetworkException() {
        CustomToast.makeCustomText(this.getContext(), R.string.msg_network_error, CustomToast.LENGTH_SHORT).show();
    }

    @Override
    public void showUnknownException() {
        CustomToast.makeCustomText(this.getContext(), R.string.msg_unknown_error, CustomToast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoadingComplete() {
        //Empty implementation
    }

    @Override
    public Dialog showLoadingDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            L.e("UserInfoDialog", "Call show loading dialog while dialog is still showing, is there a bug?");
            mProgressDialog.dismiss();
        }
        mProgressDialog = ProgressDialog.show(getContext(), null, "请稍候", true, false);
        return mProgressDialog;
    }

    @Override
    public void dismissLoadingDialog() {
        if (mProgressDialog == null || (!mProgressDialog.isShowing())) {
            L.e("UserInfoDialog", "Try to dismiss a dialog but dialog is null or already dismiss!");
            return;
        }
        mProgressDialog.dismiss();
        mProgressDialog = null;
    }

    @Override
    public void dismiss() {
        mPresenter.unsubscribeTasks();
        super.dismiss();
    }


    /**
     * 踢人按钮点击监听
     */
    public interface UserClickKickListener {
        void clickKick(String userId, String username);
    }


}
